import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import Banner from '#components/Banner/Banner'
import Layout from '#components/Layout/Layout'
import Author from './Author'

import hljs from 'highlight.js'
import javascript from 'highlight.js/lib/languages/javascript'
import marked from 'marked'
import { format } from '#utils/format'

import 'highlight.js/styles/github.css'
import './less/detail.less'
import './less/github-markdown.css'

import * as APIS from '#api/articleApi'

hljs.registerLanguage('javascript', javascript)
class Detail extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      image: '',
      description: '',
      content: '',
      date: ''
    }
  }
  componentDidMount() {
    APIS.findArticle(this.props.match.params.id).then(res => {
      this.setState(
        {
          title: res.data.title,
          image: res.data.image,
          description: res.data.description,
          content: marked(res.data.text),
          date: res.data.date
        },
        () => {
          document.querySelectorAll('pre code').forEach(block => {
            hljs.highlightBlock(block)
          })
        }
      )
    })
  }
  render() {
    return (
      <section className="detail-box">
        <Banner image={require('#assets/2.jpg')}>
          <section className="detail-title grid-row">
            <h1>{this.state.title || '咦，标题去哪了'} </h1>
            <p className="detail-desc">{this.state.description}</p>
          </section>
        </Banner>
        <div className="detail-content">
          <section className="detail-text">
            <h1>{this.state.title || '咦，标题去哪了'} </h1>
            <div className="detail-time">
              <div className="detail-time-title">发布时间</div>
              <div className="detail-time-date">
                {this.state.date ? format(this.state.date) : '0000-00-00'}
              </div>
            </div>
            <div
              className="detail-article markdown-body"
              dangerouslySetInnerHTML={{ __html: this.state.content }}
            ></div>
          </section>
          <section className="detail-info">
            <Author></Author>
          </section>
        </div>
      </section>
    )
  }
}

export default Layout(withRouter(Detail))
